<template>
  <Validator purpose="sealRemove" ref="refStep1" @submit="doSealRemove" />
</template>
<script setup>
import { reactive, toRefs, ref, inject } from "vue";
import Validator from "./_validator.vue";
import _ from "lodash";
import { http, ss, loading, toast, seal } from "@/utils";

const provideHome = inject("provideHome");
const refStep1 = ref();
const state = reactive({
  style: {},
  formData: {
    pages: "",
    sealId: "",
  },
});
const { style, formData } = toRefs(state);

const changeCurStep = curStep => {
  refStep1.value.close();
  if (curStep == 1) {
    refStep1.value.show({
      title: "扫码撤章",
    });
  }
  setTimeout(() => {
    provideHome.methods.setSealCurrentOperateName("btnSealRemove");
  }, 30);
};

/** 撤章 */
const doSealRemove = async () => {
  refStep1.value.close();
  loading.showType2();
  let [err, res] = await http.post({
    data: {
      serviceCode: "revokeElectronicSealSignature",
      featureCode: "revokeFileElectronicSealSignature",
      businessData: {
        fileId: ss.get("fileId"),
      },
    },
  });
  if (res) {
    pollingSealRemoveStatus(res.transactionId);
  } else {
    loading.close();
  }
};

/** 轮询 '撤章' 结果 */
const pollingSealRemoveStatus = async transactionId => {
  let timer;
  const _pollingStop = () => {
    if (timer) {
      clearInterval(timer);
    }
  };
  const _pollingStart = async () => {
    const [err, res] = await http.post({
      data: {
        serviceCode: "revokeElectronicSealSignature",
        featureCode: "getRevokeFileElectronicSealSignature",
        businessData: {
          transactionId,
        },
      },
    });
    if (res) {
      let { revokeStatus, revokeStatusDesc } = res;
      if (revokeStatus == 10) {
        //10:撤章进行中
        timer = setTimeout(_pollingStart, 2000);
      } else if (revokeStatus == 20) {
        //20：撤章完成
        _pollingStop();
        ss.set("fileId", res.fileId);
        console.log("newFileId", res.fileId);
        seal.previewFile(res.fileId);
      } else if (revokeStatus == 30) {
        //30：撤章失败
        toast.error(revokeStatusDesc);
        _pollingStop();
        loading.close();
      }
    } else {
      _pollingStop();
      loading.close();
    }
  };
  _pollingStart();
};

defineExpose({
  show() {
    changeCurStep(1);
  },
});
</script>
<style lang="scss"></style>
